//
// Created by 21577 on 2025/4/9.
//
#include<stdio.h>
#include<stdlib.h>

// 定义双向链表的节点结构
typedef struct Node{
    int data;
    struct Node* prev;
    struct Node* next;
}Node;
// 创建一个节点
Node* createNode(int data){
    Node* newnode = (Node*) malloc(sizeof(Node));
    if(newnode == NULL){
        printf("内存分配失败！\n");
        return NULL;
    }else{
        newnode->data = data;
        newnode->prev = NULL;
        newnode->next = NULL;
        return newnode;
    }
}
// 在链表头部创建节点
Node* insertAtHead(Node* head,int data){
    Node* newnode = createNode(data);
    if(head == NULL){
        head = newnode;
    }else{
        newnode->next = head;
        head->prev = newnode;
    }
    return newnode;
}
// 在链表的尾部创建节点
Node* insertAtTail(Node* head, int data){
    Node* newnode = createNode(data);
    if(head == NULL){
        head = newnode;
    }else{
        Node* temp = head;
        while(temp->next != NULL){
            temp = temp->next;
        }
        temp->next = newnode;
        newnode->prev = temp;
    }
    return head;
}
// 正向打印链表
void PrintForward(Node* head){
    Node* current = head;
    if(head == NULL){
        printf("链表为空！\n");
        return;
    }
    while(current != NULL){
        printf("%d  ",current->data);
        current = current->next;
    }
    printf("\n");
}
// 删除指定值的节点
Node* deleteNode(Node* head, int data){
    if(head == NULL){
        return NULL;
    }
    Node* temp = head;
    // 如果指定值为头节点
    if(temp->data == data){
        head = head->next;
        free(temp);
        return head;
    }
    while(temp!=NULL && temp->data != data){
        temp = temp->next;
    }
    if(temp == NULL)
        return NULL;
    if(temp->next != NULL)
        temp->next->prev = temp->prev;
    if(temp->prev != NULL)
        temp->prev->next = temp->next;
    free(temp);
    return head;
}
// 释放链表内存
void freeList(Node** head) {
    Node* temp = *head;
    Node* next;
    while (temp != NULL) {
        next = temp->next;
        free(temp);
        temp = next;
    }
    *head = NULL;
}
int main(){
    Node* head = NULL;
    // 在头部创建节点
    head = insertAtHead(head, 1);
    head = insertAtHead(head, 2);
    head = insertAtHead(head, 3);
    PrintForward(head);
    // 在链表的头部创建节点
    head = insertAtTail(head, 4);
    head = insertAtTail(head, 5);
    head = insertAtTail(head, 6);
    // 正向打印链表
    PrintForward(head);
    // 删除指定的节点
    head = deleteNode(head, 5);
    PrintForward(head);

    return 0;
}